package com.itheima.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.common.BaseContext;
import com.itheima.common.R;
import com.itheima.entity.ShoppingCart;
import com.itheima.service.ShoppingCartService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.List;

@RestController
@RequestMapping("/shoppingCart")
@Slf4j
public class Shoppingcontroller {
    @Autowired
    private ShoppingCartService service;
@PostMapping("/add")
    public R<ShoppingCart> add(@RequestBody ShoppingCart shoppingCart){
    log.info("购物车数据：{}",shoppingCart);
    Long currenId = BaseContext.getCurrenId();
    shoppingCart.setUserId(currenId);
    Long dishId = shoppingCart.getDishId();
    LambdaQueryWrapper<ShoppingCart> queryWrapper = new LambdaQueryWrapper<>();
    queryWrapper.eq(ShoppingCart::getUserId,currenId);
    if (dishId!=null){
        queryWrapper.eq(ShoppingCart::getDishId,dishId);
    }else {
        queryWrapper.eq(ShoppingCart::getSetmealId,shoppingCart.getSetmealId());
    }
    ShoppingCart one = service.getOne(queryWrapper);
    if (one!=null){
        Integer number = one.getNumber();
        one.setNumber(number+1);
        service.updateById(one);
    }else {
        shoppingCart.setNumber(1);
        shoppingCart.setCreateTime(LocalDateTime.now());
        service.save(shoppingCart);
        one = shoppingCart;
    }

    return R.success(one);
}

@GetMapping("/list")
    public R<List<ShoppingCart>> list(){
    log.info("购物车数据");
    LambdaQueryWrapper<ShoppingCart> queryWrapper = new LambdaQueryWrapper<>();
    queryWrapper.eq(ShoppingCart::getUserId, BaseContext.getCurrenId());
    queryWrapper.orderByDesc(ShoppingCart::getCreateTime);
    List<ShoppingCart> list = service.list(queryWrapper);
    return R.success(list);
}

@DeleteMapping("/clean")
    public R<String> delete(){
    LambdaQueryWrapper<ShoppingCart> queryWrapper = new LambdaQueryWrapper();
    queryWrapper.eq(ShoppingCart::getUserId,BaseContext.getCurrenId());
    service.remove(queryWrapper);
    return R.success("清空成功");
}
}
